package com.neu.wms.security;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author DAIJUNQIANG
 * @version 1.0
 * @description 得到用户信息，并开户认证
 * @date 2023/7/3 15:35
 */
public class LoginFilter extends AbstractAuthenticationProcessingFilter {

	//定义过滤器拦截的请求映射
	private final static String matchUrl = "/users/login";

	protected LoginFilter() {
		//TODO 对这里的matchUrlDeBug
		super(new AntPathRequestMatcher(matchUrl));
	}

	/**
	 * 获取用户登录信息，并开户认证
	 * @param request 请求
	 * @param response 响应
	 * @return Authentication 认证信息
	 */
	@Override
	public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
		//通过前台获取账号密码
		String name = request.getParameter("userName");

		logger.info("name: " + name);
		String password = request.getParameter("password");
		UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(name, password);
		//开启认证框架
		return this.getAuthenticationManager().authenticate(authenticationToken);
	}
}
